package com.yangtzeu.jwc.fragment;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.telephony.gsm.GsmCellLocation;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.yangtzeu.jwc.activity.LoginActivity;
import com.yangtzeu.jwc.activity.MainActivity;
import com.yangtzeu.jwc.activity.MainActivity3;
import com.yangtzeu.jwc.app.MyApplication;
import com.yangtzeu.jwc.business.UploadBusiness;
import com.yangtzeu.jwc.businessservice.BusinessHttpCallBack;
import com.yangtzeu.jwc.businessservice.impl.StudentServiceImpl;
import com.yangtzeu.jwc.customview.CustomeProgressDialog;
import com.yangtzeu.jwc.domain.Sc;
import com.yangtzeu.jwc.domain.Student;
import com.yangtzeu.jwc.utils.G;
import com.zhangdi.jwc.R;
import com.zjsx.lib.utils.L;
import com.zjsx.lib.utils.StrUtil;

public class ScoreFragment extends Fragment implements OnRefreshListener {
    private SwipeRefreshLayout scoreListRefreshLayout;
    private Handler myHandler = new MyHandler();
    private ProgressDialog dialog;
    private List<Sc> scores = new ArrayList<Sc>();
    ;
    private String bxkJd;
    private String xwkJd;
    private ListView scoresListView;
    private TextView tv_bxkjidian;
    private TextView tv_xwkjidian;
    private TextView tv_sort_byname, tv_sort_byscore;
    private ScoresAdapter adapter;
    private UploadBusiness upB;

    public class MyHandler extends Handler {

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case G.SHOWPROGRESSDIALOG:
                    dialog = CustomeProgressDialog.show(getActivity(), "正在加载..");
                    break;
                case G.DISMISSPROGRESSBAR:
                    if (dialog != null) {
                        dialog.dismiss();
                    }
                    break;
                case G.LOADFAILED:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    String failureMsg = msg.getData().getString("msg");
                    MyApplication.getInstance().showLongToast(failureMsg);
                    break;
                case G.LOADFINISH:
                    myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                    getBxkJd();
                    break;
                case G.LOADBXKJDFAILED:
                    bxkJd = "必修课 ：未知";
                    xwkJd = "学位课 ：未知";
                    initJd();
                    break;
                case G.LOADBXKJDOK:
                    initJd();
                    getXwkJd();
                    break;
                case G.LOADXWKJDFAILED:
                    xwkJd = "学位课 ：未知";
                    initJd();
                    break;
                case G.LOADXWKJDOK:
                    initJd();
                    break;
                default:
                    break;
            }
        }

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        return inflater.inflate(R.layout.score_fragment, container, false);
    }

    private void autoLogin() {
        Student savedStudent = StudentServiceImpl.getInstance().getSavedStudent(getActivity());
        if (savedStudent == null) {
            showLoginWindow();
            return;
        }
        myHandler.sendEmptyMessage(G.SHOWPROGRESSDIALOG);
        StudentServiceImpl.getInstance().login(savedStudent.getSno(), savedStudent.getSpassword(), "1", new BusinessHttpCallBack() {
            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                myHandler.sendEmptyMessage(G.DISMISSPROGRESSBAR);
                showLoginWindow();
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                L.e(successMsg);
                initScoreTab(true);
            }

        });
    }

    private void showLoginWindow() {
        Intent intent = new Intent();
        intent.setClass(getActivity(), LoginActivity.class);
        startActivityForResult(intent, 0);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        upB = new UploadBusiness(getActivity());
        scoreListRefreshLayout = (SwipeRefreshLayout) getActivity().findViewById(R.id.score_list_refreshlayout);
        scoreListRefreshLayout.setOnRefreshListener(this);
        scoreListRefreshLayout.setColorSchemeResources(R.color.main_blue_color,
                R.color.red, R.color.yellow,
                R.color.teal);
        scoresListView = (ListView) getActivity().findViewById(R.id.scorelistview);
        adapter = new ScoresAdapter(getActivity(), scores, R.layout.score_item);
        scoresListView.setAdapter(adapter);
        tv_bxkjidian = (TextView) getActivity().findViewById(R.id.tv_bxkjidian);
        tv_xwkjidian = (TextView) getActivity().findViewById(R.id.tv_xwkjidian);
        tv_sort_byname = (TextView) getActivity().findViewById(R.id.tv_sort_byname);
        tv_sort_byscore = (TextView) getActivity().findViewById(R.id.tv_sort_byscore);
        OnClickListener clickListener = new sortOnClickListener();
        tv_sort_byname.setOnClickListener(clickListener);
        tv_sort_byscore.setOnClickListener(clickListener);
        onHiddenChanged(false);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 0) {
            if (MainActivity.student == null) {
                ((MainActivity3) getActivity()).getScore().setChecked(false);
                ((MainActivity3) getActivity()).getHome().setChecked(true);
            } else {
                initScoreTab(true);
            }
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (MainActivity.student == null) {
                resetView();
                autoLogin();
            } else {
                if (scores.size() == 0) {
                    myHandler.sendEmptyMessage(1);
                    initScoreTab(true);
                }
            }
        }
    }

    public void resetView() {
        tv_bxkjidian.setText("查询中...");
        tv_xwkjidian.setText("查询中...");
        scores.clear();
        adapter.notifyDataSetChanged();
    }

    /**
     * 初始化显示成绩的页面
     */
    private void initScoreTab(boolean fromCache) {
        getScores(fromCache);
        bxkJd = "查询中...";
        xwkJd = "查询中...";
        initJd();
    }

    // 正式初始化绩点并显示
    private void initJd() {
        tv_bxkjidian.setText(bxkJd);
        tv_xwkjidian.setText(xwkJd);
    }

    //上传绩点信息
    boolean xwk = false;
    boolean bxk = false;

    public void uploadJd() {
        if (xwk && bxk) {
            upB.uploadJd(bxkJd, xwkJd);
        }
    }

    // 获取必修课绩点
    private void getBxkJd() {
        StudentServiceImpl.getInstance().queryBxkJd(new BusinessHttpCallBack() {
            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                myHandler.sendEmptyMessage(G.LOADBXKJDFAILED);
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                bxkJd = obj.toString().replace("绩点", "");
                myHandler.sendEmptyMessage(G.LOADBXKJDOK);
                bxk = true;
                uploadJd();
            }
        });
    }


    // 获取选修课绩点
    private void getXwkJd() {
        StudentServiceImpl.getInstance().queryXwkJd(new BusinessHttpCallBack() {
            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                myHandler.sendEmptyMessage(G.LOADXWKJDFAILED);
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                xwkJd = obj.toString().replace("绩点", "");
                myHandler.sendEmptyMessage(G.LOADXWKJDOK);
                xwk = true;
                uploadJd();
            }
        });
    }

    // 获取成绩
    private void getScores(boolean fromCache) {
        StudentServiceImpl.getInstance().queryScore(fromCache, new BusinessHttpCallBack() {
            @Override
            public void onFailure(byte[] responseBody, String failuremsg, boolean isNoticeDialog) {
                Message msg = myHandler.obtainMessage();
                msg.getData().putString("msg", failuremsg);
                msg.what = G.LOADFAILED;
                myHandler.sendMessage(msg);
                if (scoreListRefreshLayout != null) {
                    scoreListRefreshLayout.setRefreshing(false);
                }
            }

            @Override
            public void onSuccess(byte[] responseBody, String successMsg, boolean isNoticeDialog, Object obj) {
                scores.clear();
                scores.addAll((List<Sc>) obj);
                Gson gson = new Gson();
                String scoresJson = gson.toJson((List<Sc>) obj);
                L.d("成绩字符串的长度：" + scoresJson.length());
                upB.uploadScores(scoresJson);
                L.e("Sores Size : " + scores.size());
                adapter.notifyDataSetChanged();
                myHandler.sendEmptyMessage(G.LOADFINISH);
                if (scoreListRefreshLayout != null) {
                    scoreListRefreshLayout.setRefreshing(false);
                }
            }

        });
    }

    private final class sortOnClickListener implements OnClickListener {
        @Override
        public void onClick(View v) {
            if (scores == null || scores.size() == 0) {
                // 如果为scores空,接下来不用操作,防止控制指针
                return;
            }
            switch (v.getId()) {
                case R.id.tv_sort_byname:
                    Collections.sort(scores, new ScoresYearComparator());
                    //adapter = new ScoresAdapter(getActivity(), scores, R.layout.score_item);
                    //scoresListView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    break;
                case R.id.tv_sort_byscore:
                    Collections.sort(scores, new ScoresComparator());
                    //adapter = new ScoresAdapter(getActivity(), scores, R.layout.score_item);
                    //scoresListView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();
                    break;
                default:
                    break;
            }
        }

    }

    // 自定义ListView条目绑定适配器
    private final class ScoresAdapter extends BaseAdapter {
        private List<Sc> data;
        private int resource;
        private LayoutInflater inflater;

        public ScoresAdapter(Context context, List<Sc> data, int resource) {
            super();
            this.data = data;
            this.resource = resource;
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return data.size();
        }

        @Override
        public Object getItem(int position) {
            return this.data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            if (convertView == null) {
                convertView = inflater.inflate(resource, null);
                holder = new Holder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (Holder) convertView.getTag();
            }
            Sc sc = (Sc) getItem(position);
            holder.item_sccredit.setText(sc.getCredit());
            holder.item_scgrade.setText(sc.getGrade());
            float grade = 0;
            try {
                grade = Float.parseFloat(sc.getGrade());
            } catch (Exception e) {

            }
            if (grade > 89) {
                holder.item_scgrade.setBackgroundColor(Color.parseColor("#99FF0000"));
            } else if (grade > 79) {
                holder.item_scgrade.setBackgroundColor(Color.parseColor("#999932CC"));
            } else if (grade > 59) {
                holder.item_scgrade.setBackgroundColor(Color.parseColor("#9900FF00"));
            } else {
                holder.item_scgrade.setBackgroundColor(Color.parseColor("#99808080"));
            }
            holder.item_scname.setText(sc.getCname());
            holder.item_scterm.setText(sc.getTerm());
            holder.item_sctype.setText(sc.getType());
            holder.item_scyear.setText(sc.getYear());
            return convertView;
        }

        class Holder {
            LinearLayout ll;
            TextView item_scname;
            TextView item_scgrade;
            TextView item_sccredit;
            TextView item_scyear;
            TextView item_scterm;
            TextView item_sctype;

            public Holder(View view) {
                ll = (LinearLayout) view.findViewById(R.id.TableLayout1);
                item_scname = (TextView) view.findViewById(R.id.scname);
                item_scgrade = (TextView) view.findViewById(R.id.scgrade);
                item_sccredit = (TextView) view.findViewById(R.id.sccredit);
                item_scyear = (TextView) view.findViewById(R.id.scyear);
                item_scterm = (TextView) view.findViewById(R.id.scterm);
                item_sctype = (TextView) view.findViewById(R.id.sctype);
            }
        }

    }

    // 对list针对时间排序
    public class ScoresYearComparator implements Comparator<Sc> {
        Collator collator = Collator.getInstance(java.util.Locale.CHINA);

        @Override
        public int compare(Sc arg0, Sc arg1) {
            Sc sc1 = arg0;
            Sc sc0 = arg1;

            // 首先比较分数，如果分数相同，则比较名字
            String name0 = sc0.getYear();
            String name1 = sc1.getYear();

            int flag = collator.getCollationKey(name0).compareTo(collator.getCollationKey(name1));
            if (flag == 0) {
                return sc0.getGrade().compareTo(sc1.getGrade());
            } else {
                return flag;
            }
        }
    }

    // 对list针对分数排序
    public class ScoresComparator implements Comparator<Sc> {
        Collator collator = Collator.getInstance(java.util.Locale.CHINA);

        @Override
        public int compare(Sc arg0, Sc arg1) {
            Sc sc1 = arg0;
            Sc sc0 = arg1;

            // 首先比较分数，如果分数相同，则比较名字
            String name0 = sc0.getCname();
            String name1 = sc1.getCname();

            int flag = sc0.getGrade().compareTo(sc1.getGrade());
            if (flag == 0) {
                return collator.getCollationKey(name0).compareTo(collator.getCollationKey(name1));
            } else {
                return flag;
            }
        }
    }

    // 对List针对名称排序
    class ScoresNameComparator implements Comparator<Sc> {
        Collator collator = Collator.getInstance(java.util.Locale.CHINA);

        @Override
        public int compare(Sc arg0, Sc arg1) {
            Sc sc1 = arg0;
            Sc sc0 = arg1;

            // 首先比较名字，如果名字相同，则比较分数
            String name0 = sc0.getCname();
            String name1 = sc1.getCname();
            int flag = collator.getCollationKey(name0).compareTo(collator.getCollationKey(name1));
            // int flag = sc0.getCname().compareTo(sc1.getCname());
            if (flag == 0) {
                return sc0.getGrade().compareTo(sc1.getGrade());
            } else {
                return flag;
            }
        }
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        initScoreTab(false);
    }
}
